import os
import logging as log

import re  # 正则
import winreg  # windows注册表
import zipfile  # 压缩解压
import requests


# 下载chromedirver的镜像地址
base_url = 'https://storage.googleapis.com/chrome-for-testing-public/'
# 匹配前3位版本号的正则表达式
version_re = re.compile(r'^[1-9]\d*\.\d*.\d*')

# 通过注册表查询chrome版本
def getChromeVersion():
    try:
        key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Software\\Google\\Chrome\\BLBeacon')
        value, t = winreg.QueryValueEx(key, 'version')
        return version_re.findall(value)[0]  # 返回前3位版本号
    except WindowsError as e:
        # 没有安装chrome浏览器
        return "1.1.1"

# 查询Chromedriver版本
def getChromeDriverVersion():
    outstd2 = os.popen('chromedriver --version').read()
    try:
        version = outstd2.split(' ')[1]
        version = ".".join(version.split(".")[:-1])
        return version
    except Exception as e:
        return "0.0.0"

# 检查chromedirver用不用更新
def checkChromeDriverUpdate():
    chrome_version = getChromeVersion()
    log.info(f'当前chrome版本: {chrome_version}')
    driver_version = getChromeDriverVersion()
    log.info(f'当前chromedriver版本: {driver_version}')
    if chrome_version == driver_version:
        log.info("版本兼容，无需更新.")
        return
    log.info("chromedriver版本与chrome浏览器不兼容，更新中>>>")
    try:
        getLatestChromeDriver(chrome_version)
        log.info("chromedriver更新成功!")
    except requests.exceptions.Timeout:
        log.info("chromedriver下载失败，请检查网络后重试！")
    except Exception as e:
        log.info(f"chromedriver未知原因更新失败: {e}")


# 获取该chrome版本的最新driver版本号
def getLatestChromeDriver(version):
    url = f"{base_url}LATEST_RELEASE_{version}"
    # latest_version = requests.get(url).text
    latest_version = version + "." + version.split(".")[0]
    print(f"与当前chrome匹配的最新chromedriver版本为: {latest_version}")
    # 下载chromedriver
    print("开始下载chromedriver...")
    download_url = f"{base_url}{latest_version}/win64/chromedriver-win64.zip"
    print("下载地址：{}".format(download_url))
    file = requests.get(download_url)
    with open("chromedriver.zip", 'wb') as zip_file:  # 保存文件到脚本所在目录
        zip_file.write(file.content)
    print("下载完成.")




def unzip_file(zip_path, extract_to):
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        zip_ref.extractall(extract_to)
    print("解压完成.")



if __name__ == '__main__':
    checkChromeDriverUpdate()
    # zip_path = 'chromedriver.zip'  # 替换为你的zip文件路径
    # extract_to = 'chromedriver'  # 指定解压到的目录
    # unzip_file(zip_path, extract_to)